<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>铜官区口罩预约状态查看</title>
  <link href="./js/ele.css" rel="stylesheet">
  <style>
    body {
      background-image: linear-gradient( 135deg, #43CBFF 10%, #9708CC 100%);
      color: #fff;
    }
    .header {
      padding: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .header .btn {
      margin-left: 20px;
    }
    .select-input {
      width: 100%;
    }
    .qbtn {
      margin: 20px 0;
      width: 100%;
    }
    .red {
      color: #ff0000;
    }
    .frame {
      width: 100%;
      height: 500px;
    }
  </style>
</head>

<body>
  <div id="app">
    <h1>官方预约通道早已关闭, 请不要再访问了</h1>
    <h2>想感谢我, 请微信搜索  </h2><h1>zzes小组</h1>
    <!-- <strong>注意:</strong>
    <div>可以在预填写中选择药房, 随后点击快速预约可直接预约!!!</div>
    <strong>若点击提示不在预约时间内, 请持续点击直到显示 <span class="red">"您已预约"</span> 或者 <span class="red">"预约剩余人数不足，请明天再试!"</span> 才停止点击</strong>
    -->
    <div>治电平台预约成功人数: <strong>{{hasSuccessNum}}</strong>  位, 共助力获取口罩数约 <strong> {{hasSuccessNum * 5}} </strong>个; 祝大家预约成功</div> 
    <div class="header">
      <div class="btn"><el-button size="mini" type="danger" @click="open">预填写</el-button></div>
      <div class="btn"><el-button size="mini" @click="refresh">刷新(9点勿刷新)</el-button></div>
      <div class="btn" v-show="openTable"><el-button size="mini" @click="closeAndOpen"><span v-if="closeStatus">展开</span><span v-else>收起</span>小区</el-button></div>
    </div>
    <el-button class="qbtn" type="warning" @click="quickOrder">快速预约</el-button>
    <div>
      <el-button class="qbtn" type="success" @click="autoOrder">自动预约</el-button>
    </div>
    <el-switch v-model="openTable"></el-switch>
    <el-table v-if="openTable" :data="tableData" style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      ref="tableEle"
      border
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="deptId" label="药店ID" width="60">
        <template slot-scope=scope>
          <div>
            <div v-if="scope.row.searchValue">{{scope.row.deptId}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="药店名称" min-width="200">
        <template slot-scope="scope">
          <div>
            <strong >{{scope.row.deptName}}</strong>
            <span v-if="scope.row.searchValue"> (剩余预约数量: {{scope.row.searchValue}} 个)</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope=scope>
          <div>
            <el-button v-if="scope.row.searchValue" size="mini" type="primary" @click="toOrder(scope.row.deptId)">前往预约</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="药店地址" min-width="200"></el-table-column>
    </el-table>
    <el-dialog
      title="信息填写"
      :visible.sync="dialog"
      width="80%">
      <el-form ref="form" :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobilePhone">
          <el-input v-model="form.mobilePhone" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="住宅地址" prop="userAddress">
          <el-input v-model="form.userAddress" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="小区">
          <el-select class="select-input" size="mini" clearable filterable v-model="selectXq" @change="xqChange">
            <el-option v-for="v in tableData" :key="v.deptId" :value="v.deptId" :label="v.deptName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药房">
          <el-select class="select-input" size="mini" clearable filterable v-model="form.shopId">
            <el-option v-for="v in yf" :key="v.deptId" :value="v.deptId" :label="v.deptName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  <script src="./js/vue.min.js"></script>
  <script src="./js/axios.js"></script>
  <script src="./js/ele.js"></script>
  <script src="./js/bmob.js"></script>
  <script>
    Bmob.initialize('119947231f592fd5', 'qwer12')
    const query = Bmob.Query('success');
    const validPhone =  (rule, value, callback) => {
      var szReg=/(^1[3,4,5,6,7,8,9]\d{9}$)/g;
      var bChk=szReg.test(value);
      if(!bChk){
        callback(new Error('手机号码格式不正确'))
      } else {
        callback()
      }
    }
    const validateIdCard =  (rule, value, callback) => {
      // 判断如果传入的不是一个字符串，则转换成字符串
      value = typeof value === 'string' ? value : String(value)
      //正则表达式验证号码的结构
      let regx = /^[\d]{17}[0-9|X|x]{1}$/
      if (regx.test(value)) {
        // 验证前面17位数字，首先定义前面17位系数
        let sevenTeenIndex = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        // 截取参数前17位
        let front_seventeen = value.slice(0, 17)
        // 截取第18位
        let eighteen = value.slice(17, 18)
        // 这里如果是X要转换成小写，如果是数字在这里是字符串类型,则转换成数字类型，好做判断
        eighteen = isNaN(parseInt(eighteen)) ? eighteen.toLowerCase() : parseInt(eighteen)
        // 定义一个变量计算系数乘积之和余数
        let remainder = 0
        //利用循环计算前17位数与系数乘积并添加到一个数组中
        // charAt()类似数组的访问下标一样，访问单个字符串的元素,返回的是一个字符串因此要转换成数字
        for (let i = 0; i < 17; i++) {
          remainder = (remainder += parseInt(front_seventeen.charAt(i)) * sevenTeenIndex[i]) % 11
        }
        //余数对应数字数组
        let remainderKeyArr = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
        // 取得余数对应的值
        let remainderKey = remainderKeyArr[remainder] === 'X' ? remainderKeyArr[remainder].toLowerCase() : remainderKeyArr[remainder]
        console.log(remainderKey)
        console.log(eighteen)
        // 如果最后一位数字对应上了余数所对应的值，则验证合格，否则不合格,
        // 由于不确定最后一个数字是否是大小写的X，所以还是都转换成小写进行判断
        if (eighteen === remainderKey) {
          callback()
        } else {
          callback(new Error('身份证格式错误'))
        }
      } else {
        callback(new Error('身份证格式错误'))
      }
    }
    new Vue({
      el: '#app',
      data() {
        return {
          autoStatus: false,
          autoTimer: null,
          tableData: [],
          ROOTURL: 'http://122.51.46.108:8989',
          dialog: false,
          form: {
            name: '',
            mobilePhone: '',
            idCard: '',
            userAddress: '',
            shopId: ''
          },
          openTable: false,
          rules: {
            name: [
              { required: true, message: '请输入姓名', trigger: 'blur' }
            ],
            mobilePhone: [
              { required: true, validator: validPhone, trigger: 'blur' }
            ],
            idCard: [
              { required: true, validator: validateIdCard, trigger: 'blur' }
            ],
            userAddress: [
              { required: true, message: '请输入住址', trigger: 'blur' }
            ]
          },
          closeStatus: false,
          selectXq: '',
          yf: '',
          hasSuccessNum: 0
        }
      },
      async mounted() {
        // try {
        //   const info = localStorage.getItem('info')
        //   if (info) {
        //     this.form = JSON.parse(info)
        //   }  
        // } catch (error) {}
        // await this.getXq()
        // await this.getYf()

        query.get('NeQg1115')
          .then(res => res.num)
          .then(n => {
            this.hasSuccessNum = n
          })
      },
      methods: {
        autoOrder () {
          if(!this.form.name) {
            this.$message.error('名字填一下?')
            return
          }
          if ((new Date().getHours() < 8 && new Date().getMinutes() < 50) || new Date().getHours() > 9) {
            this.$message.error('当前时间段不可以进行自动预约!!!')
            this.autoTimer && clearInterval(this.autoTimer)
            return
          } 
          this.autoTimer = setInterval( async () => {
            const params = new URLSearchParams()
            Object.keys(this.form).forEach(v => {
              params.append(v, this.form[v])
            })
            const result = await axios.post(`${this.ROOTURL}/register/login`, params).then(res => res.data)
            if (result.msg.match('成功') || result.msg.match('您已预约')) {
              clearInterval(this.autoTimer)
              query.get('NeQg1115').then(res => {
                res.increment('num')
                res.save()
              }).catch(err => {
                console.log(err)
              })
            } else if (result.msg.match('不足')) {
              clearInterval(this.autoTimer)
            } else if ((new Date().getHours() < 8 && new Date().getMinutes() < 50) || new Date().getHours() > 9) {
              this.$message.error('当前时间段不可以进行自动预约!!!')
              clearInterval(this.autoTimer)
            } else if (new Date().getHours() === 9 && new Date().getMinutes() === 1) {
              clearInterval(this.autoTimer)
            }
            this.$message.error(result.msg)
          }, 200)
          
        },
        closeAndOpen () {
          this.closeStatus = !this.closeStatus
          this.tableData.forEach(v => {
            this.$refs.tableEle.toggleRowExpansion(v, !this.closeStatus)
          })
        },
        xqChange (v) {
          const yf = this.tableData.filter(x => x.deptId === v)[0].children
          this.yf = yf
        },
        async getXq() {
          const xq = await axios.post(`${this.ROOTURL}/register/getCity?parendId=101`).then(res => res.data.object)
          xq.forEach((v, i) => {
            v.children = []
            v.id = i + ''
          })
          this.tableData = xq
        },
        async getYf () {
          this.tableData.forEach(async (v, i) => {
            const yf = await axios.post(`${this.ROOTURL}/register/getCity?parendId=` + v.deptId).then(res => res.data.object)
            yf.forEach(async (u, j) => {
              u.id = i + '000' + j
              u.searchValue = '正在获取...'
              u.email = '正在获取...'
              const nums = await axios.post(`${this.ROOTURL}/register/getCityInfo?deptId=` + u.deptId).then(res => res.data.object)
              u.searchValue = nums.searchValue
              u.email = nums.email
            })
            v.children = yf
          })
        },
        async toOrder (id) {
          if(!this.form.name) {
            this.$message.error('名字填一下?')
            return
          }
          const form = JSON.parse(JSON.stringify(this.form))
          form.shopId = id
          const params = new URLSearchParams()
          Object.keys(form).forEach(v => {
            params.append(v, form[v])
          })
          const result = await axios.post(`${this.ROOTURL}/register/login`, params).then(res => res.data)
          this.$message.error(result.msg)
          if (result.msg.match('成功') || result.msg.match('您已预约')) {
            query.get('NeQg1115').then(res => {
              res.increment('num')
              res.save()
            }).catch(err => {
              console.log(err)
            })
          }
        },
        async quickOrder () {
          if(!this.form.name) {
            this.$message.error('名字填一下?')
            return
          }
          const params = new URLSearchParams()
          Object.keys(this.form).forEach(v => {
            params.append(v, this.form[v])
          })
          const result = await axios.post(`${this.ROOTURL}/register/login`, params).then(res => res.data)
          if (result.msg.match('成功') || result.msg.match('您已预约')) {
            query.get('NeQg1115').then(res => {
              res.increment('num')
              res.save()
            }).catch(err => {
              console.log(err)
            })
          }
          this.$message.error(result.msg)
        },
        open () {
          try {
            const info = localStorage.getItem('info')
            if (info) {
              this.form = JSON.parse(info)
            }  
          } catch (error) {}
          
          this.dialog = true
        },
        confirm () {
          this.$refs['form'].validate((valid) => {
            if (valid) {
              localStorage.setItem('info', JSON.stringify(this.form))
              this.dialog = false
            } else {
              localStorage.setItem('info', JSON.stringify(this.form))
              return false
            }
          })
        },
        async refresh () {
          await this.getXq()
          await this.getYf()
        }
      }
    })
  </script>
</body>

</html>